﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ResourceExtensions.cs" company="Vizioz Limited">
//   Open Source - MIT License 2011
// </copyright>
// <summary>
//   Extension methods for embedded resources
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Vizioz.Relationships
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;

    using ClientDependency.Core;

    /// <summary>
    /// Extension methods for embedded resources
    /// </summary>
    public static class ResourceExtensions
    {
        /// <summary>
        /// Get the node's domains
        /// </summary>
        /// <param name="nodeId">
        /// The node Id.
        /// </param>
        /// <returns>
        /// A culture string
        /// </returns>
        public static umbraco.cms.businesslogic.language.Language GetNodePrimaryLanguage(int nodeId)
        {
            var domains = umbraco.library.GetCurrentDomains(nodeId);

            if (domains == null || domains.Length == 0 || domains[0].Language == null)
            {
                return null;
            }

            return domains[0].Language;
        }

        /// <summary>
        /// Adds an embedded resource to the ClientDependency output by name
        /// </summary>
        /// <param name="ctl">The CTL.</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="type">The type.</param>
        public static void AddResourceToClientDependency(this Control ctl, string resourceName, ClientDependencyType type)
        {
            ctl.Page.AddResourceToClientDependency(typeof(ResourceExtensions), resourceName, type, 100);
        }

        /// <summary>
        /// Adds an embedded resource to the ClientDependency output by name
        /// </summary>
        /// <param name="page">The Page to add the resource to</param>
        /// <param name="resourceContainer">The type containing the embedded resourcre</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="type">The type.</param>
        /// <param name="priority">The priority.</param>
        public static void AddResourceToClientDependency(this Page page, Type resourceContainer, string resourceName, ClientDependencyType type, int priority)
        {
            // get the urls for the embedded resources           
            var resourceUrl = page.ClientScript.GetWebResourceUrl(resourceContainer, resourceName);
            var target = page.Header;

            // if there's no <head runat="server" /> don't throw an exception.
            if (target != null)
            {
                // Umbraco v4.5.x shipped with earlier version of ClientDependency - which had an issue with querystrings in virtual paths.
                switch (type)
                {
                    case ClientDependencyType.Css:
                        target.Controls.Add(
                            new LiteralControl("<link type='text/css' rel='stylesheet' href='" + page.Server.HtmlEncode(resourceUrl) + "' />"));
                        break;

                    case ClientDependencyType.Javascript:
                        target.Controls.Add(
                            new LiteralControl("<script type='text/javascript' src='" + page.Server.HtmlEncode(resourceUrl) + "'></script>"));
                        break;

                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// Get related documents.
        /// </summary>
        /// <param name="nodeId">
        /// The node Id.
        /// </param>
        /// <param name="numberOfRelationships">
        /// Number of relationships
        /// </param>
        /// <returns>
        /// Related documents.
        /// </returns>
        public static string GetRelatedDocuments(int nodeId, string numberOfRelationships)
        {
            var documentId = nodeId;
            var relations = umbraco.library.GetRelatedNodes(documentId);

            var strHtml = new StringBuilder();
            strHtml.Append("<ul style='list-style: none; margin-left: 0px; padding-left: 0px;' class='f16' alt='" + DateTime.Now + "'>");

            if (relations.Length != 0)
            {
                foreach (var relation in relations)
                {
                    if (relation.Child.Id == documentId)
                    {
                        strHtml.Append(GetRelatedDocument(relation.Parent.Id, relation.Parent.Text));
                    }

                    if (relation.Parent.Id == documentId)
                    {
                        strHtml.Append(GetRelatedDocument(relation.Child.Id, relation.Child.Text));
                    }
                }
            }

            if (int.Parse(numberOfRelationships) > 0)
            {
                var viziozNumberOfRelationships = int.Parse(numberOfRelationships);

                if (viziozNumberOfRelationships > relations.Length)
                {
                    strHtml.Append(GetRelatedDocument(0, "Add a new relationship"));
                }
            }
            else
            {
                // If there is no maximum, allow additional relationships to be added.
                strHtml.Append(GetRelatedDocument(0, "Add a new relationship"));
            }

            strHtml.Append("</ul>");

            return strHtml.ToString();
        }

        /// <summary>
        /// Get related document interface.
        /// </summary>        
        /// <param name="nodeId">Node identifier.</param>
        /// <param name="nodeTitle">Node title text.</param>
        /// <returns>Related document html interace.</returns>
         internal static StringBuilder GetRelatedDocument(int nodeId, string nodeTitle)
        {
            var strHtml = new StringBuilder();

            strHtml.Append("<li class='flag");
            if (nodeId != 0)
            {
                var language = GetNodePrimaryLanguage(nodeId);

                if (language != null)
                {
                    var culture = language.CultureAlias;

                    var country = culture.Substring(culture.IndexOf("-") + 1);

                    if (country.Length > 0)
                    {
                        strHtml.Append(" " + country.ToLower() + "'");
                        strHtml.Append(" title='" + language.FriendlyName + "'");
                    }
                    else
                    {
                        strHtml.Append("'");
                    }
                }
                else
                {
                    strHtml.Append("'");
                }
            }
            else
            {
                strHtml.Append("'");
            }

            strHtml.Append(">");

            strHtml.Append(
                string.Format("<input type='hidden' name='document_picker_{0}_ContentIdValue' id='document_picker_{0}_ContentIdValue' value='{0}' />", nodeId));
            strHtml.Append(
                nodeId == 0
                    ? string.Format("<span id='document_picker_{0}_btns' style='display: none;'>", nodeId)
                    : string.Format("<span id='document_picker_{0}_btns'>", nodeId));

            strHtml.Append(string.Format("<span id='document_picker_{0}_title' style='font-weight:bold; text-decoration: underline; cursor: pointer;' onclick=\"location.href='/umbraco/editContent.aspx?id={0}'\">{1}</span>&nbsp;&nbsp;", nodeId, nodeTitle));
            strHtml.Append(
                string.Format(
                    "<a href='javascript:mc_document_picker_{0}.ClearSelection();' onclick=\"javascript:this.parentNode.parentNode.className='flag';\" style='color:red;' title='Delete'>Delete</a>&nbsp;&nbsp;", nodeId));
            strHtml.Append("</span>");
            strHtml.Append(string.Format("<a href='javascript:mc_document_picker_{0}.LaunchPicker();'>Choose...</a>", nodeId));
            strHtml.Append("<script type='text/javascript'>");
            strHtml.Append(
                string.Format("var mc_document_picker_{0} = new Umbraco.Controls.TreePicker('document_picker_{0}','Choose Content','document_picker_{0}_ContentIdValue','document_picker_{0}_title','/umbraco/dialogs/treepicker.aspx?rnd={1}&id={0}&treeType=content&contextMenu=true&isDialog=false&app=content',320,400,true,'/umbraco');", nodeId, DateTime.Now.Ticks));
            strHtml.Append("</script>");
            strHtml.Append("</li>");

            return strHtml;
        }
    }
}